﻿Imports Tajan.Monitoring.Entities
Imports Tajan.Monitoring.Service

Public Class Manager

    Private WithEvents connectionService As ConnectionService
    Private serviceFactory As ServiceFactory

    Private Function GetMonitoringHub() As SignalR.Hubs.IHubContext
        Return SignalR.GlobalHost.ConnectionManager.GetHubContext(Of MonitoringHub)()
    End Function

    Private Function GetServerHub() As SignalR.Hubs.IHubContext
        Return SignalR.GlobalHost.ConnectionManager.GetHubContext(Of ServerHub)()
    End Function

    Public Sub New()
        Me.serviceFactory = New ServiceFactory
        Me.connectionService = Me.serviceFactory.GetService(Of ConnectionService)()
    End Sub

    Public Function CreateNewConnection(request As HttpRequest) As Connection

        Dim newConnection As New Connection

        With newConnection

            .UserHostName = IIf(String.IsNullOrEmpty(request.UserHostName), String.Empty, request.UserHostName)
            .UserIP = IIf(String.IsNullOrEmpty(request.UserHostAddress), String.Empty, request.UserHostAddress)
            .UserAgent = IIf(String.IsNullOrEmpty(request.UserAgent), String.Empty, request.UserAgent)
            .StartDate = Now
            .EndDate = Now
            .IsAvtive = True

            .Browser = New Browser
            With .Browser
                .Name = request.Browser.Type
                .MajorVersion = request.Browser.MajorVersion
                .MinorVersion = request.Browser.MinorVersion
                .Version = request.Browser.Version
                .Type = request.Browser.Browser
            End With

        End With

        Me.connectionService.CreateNewConnection(newConnection)

        GetServerHub.Clients.onOpenConnection(newConnection.Browser.Name, newConnection.UserIP, newConnection.UserHostName, newConnection.StartDate)

        Return newConnection

    End Function

    Public Sub AddPageView(pageViewInfo As Client.PageViewInfo)
        Dim pageview = Me.connectionService.NewPageView(pageViewInfo, HttpContext.Current.User.Identity.Name)
        GetServerHub.Clients.onPageView(pageview.Domain.Name, pageview.Page, pageview.ClientUsername, pageview.ServerUsername, pageview.StartDate)
    End Sub

    Public Function GetConnectionById(connectionId As Long) As Connection
        Return Me.connectionService.GetConnectionById(connectionId)
    End Function

    Public Function GetLiveConnections() As List(Of Connection)
        Return Me.connectionService.GetLiveConnections()
    End Function

    Public Sub Disconnected(connectionId As Long)
        Me.connectionService.Disconnected(connectionId)
    End Sub

End Class
